package com.software.levelupserver.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.software.levelupserver.utils.ResultVOUtil;
import com.software.levelupserver.vo.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AppAuthenticationFailHandler implements AuthenticationFailureHandler {

    @Resource
    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Result error = ResultVOUtil.error("密码错误");
        String responseJson = objectMapper.writeValueAsString(error);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.println(responseJson);
        writer.flush();
    }
}
